import os
import json
import tempfile
from typing import Dict, Any, Optional
import logging

from .converters.docx_converter import DocxConverter
from .converters.markdown_converter import MarkdownConverter
from .converters.pdf_converter import PdfConverter

logger = logging.getLogger(__name__)

class ConverterService:
    """文档转换服务"""
    
    def __init__(self):
        self.converters = {
            'docx': DocxConverter(),
            'md': MarkdownConverter(),
            'pdf': PdfConverter()
        }
    
    def convert(self, input_path: str, source_format: str, target_format: str, 
                options: str = '{}') -> str:
        """
        转换文档格式
        
        Args:
            input_path: 输入文件路径
            source_format: 源格式 (docx, md, pdf)
            target_format: 目标格式 (docx, md, pdf)
            options: 转换选项 (JSON字符串)
            
        Returns:
            转换后文件的路径
        """
        try:
            # 解析选项
            conversion_options = json.loads(options) if options else {}
            
            # 验证格式
            if source_format not in self.converters:
                raise ValueError(f"不支持的源格式: {source_format}")
            if target_format not in self.converters:
                raise ValueError(f"不支持的目标格式: {target_format}")
            
            # 如果源格式和目标格式相同，直接返回原文件
            if source_format == target_format:
                return input_path
            
            # 创建临时输出文件
            output_fd, output_path = tempfile.mkstemp(suffix=f'.{target_format}')
            os.close(output_fd)
            
            # 执行转换
            conversion_method = f"convert_{source_format}_to_{target_format}"
            if hasattr(self, conversion_method):
                # 直接转换
                getattr(self, conversion_method)(input_path, output_path, conversion_options)
            else:
                # 通过中间格式转换
                self._convert_via_intermediate(
                    input_path, output_path, source_format, target_format, conversion_options
                )
            
            logger.info(f"成功转换 {source_format} -> {target_format}: {input_path} -> {output_path}")
            return output_path
            
        except Exception as e:
            logger.error(f"转换失败 {source_format} -> {target_format}: {str(e)}")
            raise
    
    def _convert_via_intermediate(self, input_path: str, output_path: str,
                                source_format: str, target_format: str,
                                options: Dict[str, Any]):
        """通过中间格式进行转换"""
        # 使用Markdown作为中间格式
        intermediate_format = 'md'
        
        # 第一步：转换为中间格式
        temp_fd, temp_path = tempfile.mkstemp(suffix=f'.{intermediate_format}')
        os.close(temp_fd)
        
        try:
            first_method = f"convert_{source_format}_to_{intermediate_format}"
            if hasattr(self, first_method):
                getattr(self, first_method)(input_path, temp_path, options)
            else:
                raise ValueError(f"不支持的转换路径: {source_format} -> {intermediate_format}")
            
            # 第二步：从中间格式转换为目标格式
            second_method = f"convert_{intermediate_format}_to_{target_format}"
            if hasattr(self, second_method):
                getattr(self, second_method)(temp_path, output_path, options)
            else:
                raise ValueError(f"不支持的转换路径: {intermediate_format} -> {target_format}")
                
        finally:
            # 清理临时文件
            if os.path.exists(temp_path):
                os.unlink(temp_path)
    
    # Word -> Markdown
    def convert_docx_to_md(self, input_path: str, output_path: str, options: Dict[str, Any]):
        """Word转Markdown"""
        content = self.converters['docx'].to_markdown(input_path, options)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(content)
    
    # Word -> PDF
    def convert_docx_to_pdf(self, input_path: str, output_path: str, options: Dict[str, Any]):
        """Word转PDF"""
        self.converters['docx'].to_pdf(input_path, output_path, options)
    
    # Markdown -> Word
    def convert_md_to_docx(self, input_path: str, output_path: str, options: Dict[str, Any]):
        """Markdown转Word"""
        with open(input_path, 'r', encoding='utf-8') as f:
            content = f.read()
        self.converters['md'].to_docx(content, output_path, options)
    
    # Markdown -> PDF
    def convert_md_to_pdf(self, input_path: str, output_path: str, options: Dict[str, Any]):
        """Markdown转PDF"""
        with open(input_path, 'r', encoding='utf-8') as f:
            content = f.read()
        self.converters['md'].to_pdf(content, output_path, options)
    
    # PDF -> Markdown
    def convert_pdf_to_md(self, input_path: str, output_path: str, options: Dict[str, Any]):
        """PDF转Markdown"""
        content = self.converters['pdf'].to_markdown(input_path, options)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(content)
    
    # PDF -> Word
    def convert_pdf_to_docx(self, input_path: str, output_path: str, options: Dict[str, Any]):
        """PDF转Word"""
        # 先转换为Markdown，再转换为Word
        md_content = self.converters['pdf'].to_markdown(input_path, options)
        self.converters['md'].to_docx(md_content, output_path, options)
    
    def get_supported_conversions(self) -> Dict[str, list]:
        """获取支持的转换类型"""
        return {
            'docx': ['md', 'pdf'],
            'md': ['docx', 'pdf'],
            'pdf': ['md', 'docx']
        } 